package com.yjd.merchant.app.api.project;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yjd.comm.base.control.MerchantBaseControl;
import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.base.model.PagerModel;
import com.yjd.comm.enums.ReferenceTypeEnum;
import com.yjd.comm.fs.util.FileUtil;
import com.yjd.comm.merchant.dto.ProjectSummaryInfoDto;
import com.yjd.comm.merchant.model.MerchantProjectVerifyModel;
import com.yjd.comm.merchant.service.IMerchantProjectVerifyService;
import com.yjd.comm.project.model.PrjCategoryModel;
import com.yjd.comm.project.model.ProjectModel;
import com.yjd.comm.project.model.ProjectRateModel;
import com.yjd.comm.project.service.IPrjCategoryService;
import com.yjd.comm.project.service.IProjectService;
import com.yjd.comm.resource.model.ResourceModel;
import com.yjd.comm.system.util.SysParamUtil;
import com.yjd.comm.util.ArithUtil;
import com.yjd.comm.util.FrameUtil;
import com.yjd.comm.util.ServletUtil;
import com.yjd.comm.util.StringUtil;
import com.yjd.comm.vo.Constant;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import java.util.*;

/**
 * 商户APP 项目操作
 * Created by yangchangyan on 2017/11/28.
 */
@Controller("com.yjd.merchant.app.api.project.ProjectControl")
@Scope("prototype")
@RequestMapping("/merchant/project")
public class ProjectControl extends MerchantBaseControl {

    @Resource
    private IPrjCategoryService prjCategoryService;

    @Resource
    private IProjectService projectService;

    @Resource
    private IMerchantProjectVerifyService merchantProjectVerifyService;

    /**
     * 商品列表
     *
     * @param category_id 项目分类id（0 全部）
     * @param is_used 商品售卖状态 0：待售中(没有启用) 1：在售中（启用） 2：全部商品
     * @return
     * @throws
     */
    @RequestMapping(value = "/list")
    public void projectList(Long category_id, Integer is_used) throws Exception{

        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);
        paramMap.put("org_id", super.getMerchantSession().getOrg_id());
        if(null != category_id && category_id.intValue() != 0){
            paramMap.put("category_id", category_id);
        }
        if(null != is_used && is_used.intValue() != 2){
            // 是否启用 0否 1是
            paramMap.put("is_used", is_used);
        }
        paramMap.put("sort", "create_time desc");
        paramMap.put("rows", "10");

        List<ProjectSummaryInfoDto> projectSummaryInfoDtos = new ArrayList<ProjectSummaryInfoDto>();
        PagerModel projectPage = this.projectService.getPageModel(paramMap, DbWREnums.READ);
        List<ProjectModel> projects = projectPage.getDataList();
        if(null != projects && projects.size() > 0){
            ProjectSummaryInfoDto infoDto = null;
            for(ProjectModel p : projects){
                infoDto = new ProjectSummaryInfoDto();
                infoDto.setProject_id(p.getProject_id());
                infoDto.setAct_price(p.getAct_price());
                infoDto.setIs_used(p.getIs_used());
                infoDto.setProject_name(p.getProject_name());
                projectSummaryInfoDtos.add(infoDto);
            }
        }

        this.successData(FrameUtil.newHashMap("projectSummaryInfo", projectSummaryInfoDtos));
    }

    /**
     * 商品编辑
     *
     * @param project_id 项目id
     * @param
     * @return
     * @throws
     */
    @RequestMapping(value = "/edit")
    public void projectEditInfo(Long project_id) throws Exception{
        if(project_id==null){
            FrameUtil.throwBaseException1("请求参数不能为空！");
        }
        ProjectModel project = this.projectService.getModelById(project_id, DbWREnums.READ);
        if(null == project){
            this.errorMsg("商品不存在");
            return;
        }

        Long org_id = super.getMerchantSession().getOrg_id();
        if(org_id.longValue() != project.getOrg_id().longValue()){
            this.errorMsg("当前商品不属于您的机构");
            return;
        }

        Map projectInfo = FrameUtil.newHashMap();
        projectInfo.put("project_name",project.getProject_name());
        projectInfo.put("category_id",project.getCategory_id());
        projectInfo.put("project_price",project.getProject_price());
        projectInfo.put("intro",project.getIntro());
        projectInfo.put("time_limit",project.getTime_limit());
        projectInfo.put("times",project.getTimes());
        projectInfo.put("project_pic",ServletUtil.getFileUrl(project.getProject_pic()));
        projectInfo.put("project_id",project.getProject_id());
        projectInfo.put("is_used",project.getIs_used());

        PrjCategoryModel categoryModel = prjCategoryService.getModelById(project.getCategory_id(), DbWREnums.READ);
        projectInfo.put("category_name",categoryModel==null?"":categoryModel.getName());

        this.successData(FrameUtil.newHashMap("projectInfo", projectInfo));
    }

    /**
     * 商品编辑保存
     *
     * @param info 编辑后的商品信息
     * @param
     * @return
     * @throws
     */
    @RequestMapping(value = "/edit/submit")
    public void projectEditSubmit(ProjectSummaryInfoDto info) throws Exception{
        if(     null == info
                || null == info.getProject_price()
                || null == info.getAct_price()
                || null == info.getPayment()
                || null == info.getRateList()
                || 0 == info.getRateList().size()
                || info.getProject_price() < 0
                || info.getAct_price() < 0
                || info.getPayment() < 0){
            this.errorMsg("信息不正确，请重新检查。");
            return;
        }

        // 是否上架 0否 1是 （不为1则置为0，防止其他数据上传）
        if(1 != info.getIs_used().intValue()){
            info.setIs_used(0);
        }

        // 检查价格是否正确
        info.setLoan_price(ArithUtil.sub(info.getAct_price(), info.getPayment()));
        if(info.getLoan_price() < 0){
            this.errorMsg("价格信息不正确，请重新检查。");
            return;
        }

        // 检查期数是否正确
        String defaultPeriod = SysParamUtil.getValue(Constant.SysParamKeyEnum.MFQ_PERIODS_CONFIG);
        List<Integer> periodsList = StringUtil.getObject(defaultPeriod, List.class);
        Map latestRateConfig = new HashMap();
        for(ProjectRateModel rateConfigModel : info.getRateList()){
            if(periodsList.contains(rateConfigModel.getLimit())){
                latestRateConfig.put(rateConfigModel.getLimit().toString(), rateConfigModel.getRate().toString());
                continue;
            }

            this.errorMsg("分期信息不正确，请重新检查。");
            return;
        }

        // 更新项目信息
        ProjectModel projectModel = projectService.getModelById(info.getProject_id(), DbWREnums.READ);
        ProjectModel updateProject = new ProjectModel();
        updateProject.setProject_id(projectModel.getProject_id());
        updateProject.setWhere_version(projectModel.getVersion());
        updateProject.setProject_price(info.getProject_price());
        updateProject.setAct_price(info.getAct_price());
        updateProject.setPayment(info.getPayment());
        updateProject.setLoan_price(info.getLoan_price());
        updateProject.setIs_used(info.getIs_used());
        updateProject.setRate_config(JSON.toJSONString(latestRateConfig));
        projectService.update(updateProject);

        this.successMsg("修改成功");
    }

    /**
     * 项目分类列表
     *
     * @throws
     */
    @RequestMapping(value = "/category")
    public void projectCategory() throws Exception {
        List<PrjCategoryModel> projectCgy = prjCategoryService.getModelList(FrameUtil.newHashMap("is_used", "1"), DbWREnums.READ);
        PrjCategoryModel first = new PrjCategoryModel();
        first.setId(0L);
        first.setName("全部");
        projectCgy.add(0, first);
        this.successData(FrameUtil.newHashMap("cgyList", projectCgy));
    }

    /**
     * 项目分类列表(去掉【全部】选项)
     *
     * @throws
     */
    @RequestMapping(value = "/new/category")
    public void newPrjCategory() throws Exception {
        List<PrjCategoryModel> projectCgy = prjCategoryService.getModelList(FrameUtil.newHashMap("is_used", "1"), DbWREnums.READ);
        this.successData(FrameUtil.newHashMap("cgyList", projectCgy));
    }


    /**
     * 商户添加商品申请
     * @throws Exception
     */
    @RequestMapping(value = "/apply")
    public void projectApply(MultipartHttpServletRequest request)throws Exception{

         String project_name = request.getParameter("project_name");
         String category = request.getParameter("category_id");
         String project_price = request.getParameter("project_price");
         String intro = request.getParameter("intro");
         String time_limit = request.getParameter("time_limit");
         String times = request.getParameter("times");

         if(StringUtil.isEmpty(project_name)){
             FrameUtil.throwBaseException1("请输入标题");
         }

         if(project_name.length()>15){
             FrameUtil.throwBaseException1("标题不能超过15个字");

         }

         if(StringUtil.isEmpty(category)){
             FrameUtil.throwBaseException1("请选择类目");
         }


         if(StringUtil.isEmpty(project_price)){
             FrameUtil.throwBaseException1("请输入商品售价");
         }


         if(StringUtil.isEmpty(intro)){
             FrameUtil.throwBaseException1("请输入商品简介");
         }

         if(intro.length()>150){
             FrameUtil.throwBaseException1("商品简介不能超过150个字");
         }


         if(StringUtil.isEmpty(time_limit)){
             FrameUtil.throwBaseException1("请输入服务时长");
         }

         if(StringUtil.isEmpty(times)){
             FrameUtil.throwBaseException1("请输入服务次数");
         }

        String id = request.getParameter("id");
        Long mac_id = super.getMerchantId();

        String image_path = "";
        List<MultipartFile> multipartFiles = request.getMultiFileMap().get("Filedata");

        if(!StringUtil.isEmpty(id)){
              MerchantProjectVerifyModel verifyModel =  merchantProjectVerifyService.getModelById(id,DbWREnums.READ);
              if(verifyModel==null){
                  FrameUtil.throwBaseException1("您修改的记录不存在");
              }

              if(mac_id.intValue()!= verifyModel.getOrg_id().intValue()){
                  FrameUtil.throwBaseException1("您修改的记录不属于当前商户");
              }

              if(verifyModel.getStatus().intValue()!=2){
                  FrameUtil.throwBaseException1("您请求的记录当前状态不可修改");
              }

              if(multipartFiles!=null&&!multipartFiles.isEmpty()){
                  //如果不为空情况则有修改图片，先重新删除老图片，再传新的图片
                  if(multipartFiles.size()>1){
                      FrameUtil.throwBaseException1("上传图片只能为一张");
                  }
                  //先将新图片上传
                  image_path = FileUtil.uploadProjectApplyFileToRemote(multipartFiles.get(0), ReferenceTypeEnum.PROJECT_APPLY,mac_id);
                  //删除掉老图片
                  FileUtil.delteOssFile(verifyModel.getProject_pic());
              }
        }else {
            if(multipartFiles!=null&&!multipartFiles.isEmpty()){
                if(multipartFiles.size()>1){
                    FrameUtil.throwBaseException1("上传图片只能为一张");
                }
                image_path = FileUtil.uploadProjectApplyFileToRemote(multipartFiles.get(0), ReferenceTypeEnum.PROJECT_APPLY,mac_id);
            }

        }

        Long currtime = FrameUtil.getTime();

         if(!StringUtil.isEmpty(id)){

             Map updatParam = FrameUtil.newHashMap();
             updatParam.put("category_id",Integer.parseInt(category));
             updatParam.put("project_name",project_name);
             updatParam.put("org_id",mac_id);
             updatParam.put("intro",intro);
             updatParam.put("project_price",Double.parseDouble(project_price));
             updatParam.put("time_limit",Integer.parseInt(time_limit));
             updatParam.put("times",Integer.parseInt(times));
             updatParam.put("project_pic",StringUtil.isEmpty(image_path)?null:image_path);
             updatParam.put("status",0);
             updatParam.put("update_time",currtime);
             updatParam.put("id",Long.parseLong(id));
             updatParam.put("where_status",2);

             if(merchantProjectVerifyService.updateByMap(updatParam)!=1){
                 FrameUtil.throwBaseException1("修改商品失败,请重试！");
             }
             this.successMsg("修改商品成功");

         }else {
             MerchantProjectVerifyModel model = new MerchantProjectVerifyModel();
             model.setCategory_id(Integer.parseInt(category));
             model.setProject_name(project_name);
             model.setOrg_id(mac_id);
             model.setIntro(intro);
             model.setProject_price(Double.parseDouble(project_price));
             model.setTime_limit(Integer.parseInt(time_limit));
             model.setTimes(Integer.parseInt(times));
             model.setProject_pic(image_path);
             model.setStatus(0);
             model.setUpdate_time(currtime);
             model.setAdd_time(currtime);
             merchantProjectVerifyService.insert(model);
             this.successMsg("添加商品申请成功");
         }

     }

    @RequestMapping(value = "/apply/info")
    public void applyInfo(Long id) throws Exception{
        MerchantProjectVerifyModel model = this.merchantProjectVerifyService.getModelById(id, DbWREnums.READ);
        if(null == model){
            this.errorMsg("您申请记录不存在");
            return;
        }

        Long org_id = super.getMerchantSession().getOrg_id();
        if(org_id.longValue() != model.getOrg_id().longValue()){
            this.errorMsg("您请求的记录不属于当前商户");
            return;
        }

        model.setProject_pic(ServletUtil.getFileUrl(model.getProject_pic()));
        this.successData(FrameUtil.newHashMap("model", model));
    }


    @RequestMapping(value = "/apply/list")
    public void applyList() throws Exception{
        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);
        paramMap.put("org_id",super.getMerchantId());
        paramMap.put("remove_status",1);
        paramMap.put("sort", "id desc");
        this.successData(FrameUtil.newHashMap("page",
                this.merchantProjectVerifyService.getPageModel(paramMap,DbWREnums.READ)));
    }


    /**
     * 项目上架
     * @param project_id
     * @throws Exception
     */
    @RequestMapping(value = "/open", method = RequestMethod.POST)
    public void projectOpen(Long project_id) throws Exception {
        if (project_id == null) {
            FrameUtil.throwBaseException1("请求参数不能为空");
        }
        projectService.openProject(super.getMerchantId(),project_id);
        this.successMsg("项目上架成功");
    }

    /**
     * 项目下架
     * @param project_id
     * @throws Exception
     */
    @RequestMapping(value = "/close", method = RequestMethod.POST)
    public void projectClose(Long project_id) throws Exception {
        if (project_id == null) {
            FrameUtil.throwBaseException1("请求参数不能为空");
        }
        projectService.colseProject(super.getMerchantId(),project_id);
        this.successMsg("项目下架成功");
    }
}
